<template>
  <div class="message-management">

    <el-card>
      <div slot="header" class="card-header">
        <div class="header-info">
          <h3 class="card-title">
            <i class="el-icon-message"></i>
            消息管理
          </h3>
          <p class="card-subtitle">管理系统消息和群发通知</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showBroadcastDialog" icon="el-icon-s-promotion">
            群发消息
          </el-button>
        </div>
      </div>

      <!-- 消息统计 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon total-icon">
                <i class="el-icon-message"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.totalMessages }}</div>
                <div class="stat-label">总消息数</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon unread-icon">
                <i class="el-icon-warning"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.unreadMessages }}</div>
                <div class="stat-label">未读消息</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon broadcast-icon">
                <i class="el-icon-s-promotion"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.broadcastMessages }}</div>
                <div class="stat-label">群发消息</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon system-icon">
                <i class="el-icon-setting"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.systemMessages }}</div>
                <div class="stat-label">系统消息</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 消息列表 -->
      <div class="message-list-section">
        <div class="filter-bar">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-select v-model="searchForm.type" placeholder="消息类型" clearable>
                <el-option label="全部" value=""></el-option>
                <el-option label="系统消息" value="system"></el-option>
                <el-option label="劳务消息" value="labor"></el-option>
                <el-option label="群发消息" value="broadcast"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-input
                v-model="searchForm.keyword"
                placeholder="搜索消息标题或内容"
                prefix-icon="el-icon-search"
                clearable
              />
            </el-col>
            <el-col :span="8">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
            </el-col>
          </el-row>
        </div>

        <el-table :data="messageList" v-loading="loading" stripe>
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="type" label="类型" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="getTypeColor(scope.row.type)" size="small">
                {{ getTypeName(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
          <el-table-column prop="senderName" label="发送者" width="120" />
          <el-table-column prop="receiverInfo" label="接收者" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.receiverId">{{ scope.row.receiverName || '指定用户' }}</span>
              <el-tag v-else type="success" size="small">所有用户</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="发送时间" width="160">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="info" @click="handleView(scope.row)" plain>查看</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)" plain>删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-area">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          />
        </div>
      </div>
    </el-card>

    <!-- 群发消息对话框 -->
    <el-dialog
      title="群发消息"
      :visible.sync="broadcastDialogVisible"
      width="800px"
      @close="handleBroadcastDialogClose"
    >
      <el-form
        :model="broadcastForm"
        :rules="broadcastRules"
        ref="broadcastForm"
        label-width="100px"
      >
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="broadcastForm.title" placeholder="请输入消息标题" />
        </el-form-item>
        
        <el-form-item label="消息内容" prop="content">
          <div class="message-templates" style="margin-bottom: 10px;">
            <el-button size="mini" type="text" @click="useTemplate('welcome')">欢迎模板</el-button>
            <el-button size="mini" type="text" @click="useTemplate('maintenance')">维护通知</el-button>
            <el-button size="mini" type="text" @click="useTemplate('activity')">活动通知</el-button>
            <el-button size="mini" type="text" @click="useTemplate('security')">安全提醒</el-button>
          </div>
          <el-input
            v-model="broadcastForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入消息内容"
          />
        </el-form-item>
        
        <el-form-item label="发送对象" prop="targetType">
          <el-radio-group v-model="broadcastForm.targetType">
            <el-radio label="all">所有用户</el-radio>
            <el-radio label="school">指定学校</el-radio>
            <el-radio label="user">指定用户</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="broadcastForm.targetType === 'school'" label="选择学校">
          <el-select
            v-model="broadcastForm.targetSchoolIds"
            multiple
            placeholder="请选择学校"
            style="width: 100%"
          >
            <el-option
              v-for="school in schoolOptions"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="broadcastForm.targetType === 'user'" label="用户ID">
          <el-input
            v-model="userIdInput"
            placeholder="请输入用户ID，多个用逗号分隔"
            @blur="parseUserIds"
          />
          <div v-if="broadcastForm.targetUserIds.length > 0" class="selected-users">
            <el-tag
              v-for="userId in broadcastForm.targetUserIds"
              :key="userId"
              closable
              @close="removeUserId(userId)"
              style="margin: 5px 5px 0 0"
            >
              用户 {{ userId }}
            </el-tag>
          </div>
        </el-form-item>
        
        <el-form-item label="消息优先级" prop="priority">
          <el-radio-group v-model="broadcastForm.priority">
            <el-radio :label="1">低</el-radio>
            <el-radio :label="2">中</el-radio>
            <el-radio :label="3">高</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="发送方式">
          <el-radio-group v-model="broadcastForm.sendImmediately">
            <el-radio :label="true">立即发送</el-radio>
            <el-radio :label="false">定时发送</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="!broadcastForm.sendImmediately" label="定时时间">
          <el-date-picker
            v-model="broadcastForm.scheduledTime"
            type="datetime"
            placeholder="选择发送时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="broadcastDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBroadcast" :loading="broadcastLoading">
          {{ broadcastForm.sendImmediately ? '立即发送' : '定时发送' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 消息详情对话框 -->
    <el-dialog
      title="消息详情"
      :visible.sync="detailDialogVisible"
      width="600px"
    >
      <div v-if="currentMessage" class="message-detail">
        <div class="detail-item">
          <label>消息类型:</label>
          <el-tag :type="getTypeColor(currentMessage.type)" size="small">
            {{ getTypeName(currentMessage.type) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>消息标题:</label>
          <p>{{ currentMessage.title }}</p>
        </div>
        <div class="detail-item">
          <label>消息内容:</label>
          <p class="content-text">{{ currentMessage.content }}</p>
        </div>
        <div class="detail-item">
          <label>发送者:</label>
          <p>{{ currentMessage.senderName }}</p>
        </div>
        <div class="detail-item">
          <label>接收者:</label>
          <p>{{ currentMessage.receiverId ? (currentMessage.receiverName || '指定用户') : '所有用户' }}</p>
        </div>
        <div class="detail-item">
          <label>发送时间:</label>
          <p>{{ formatDate(currentMessage.createTime) }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "MessageManagement",
  data() {
    return {
      loading: false,
      broadcastLoading: false,
      messageList: [],
      schoolOptions: [],
      stats: {
        totalMessages: 0,
        unreadMessages: 0,
        broadcastMessages: 0,
        systemMessages: 0
      },
      searchForm: {
        type: '',
        keyword: '',
        dateRange: []
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      broadcastDialogVisible: false,
      detailDialogVisible: false,
      currentMessage: null,
      userIdInput: '',
      broadcastForm: {
        title: '',
        content: '',
        targetType: 'all',
        targetSchoolIds: [],
        targetUserIds: [],
        priority: 2,
        sendImmediately: true,
        scheduledTime: ''
      },
      broadcastRules: {
        title: [
          { required: true, message: '请输入消息标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入消息内容', trigger: 'blur' }
        ],
        targetType: [
          { required: true, message: '请选择发送对象', trigger: 'change' }
        ]
      }
    }
  },
  async created() {
    await this.loadMessageList()
    await this.loadStats()
    await this.loadSchoolOptions()
  },
  methods: {
    async loadMessageList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await this.$http.get("/admin/messages", { params })
        if (response.data.code === 200) {
          this.messageList = response.data.data.records || []
          this.pagination.total = response.data.data.total || 0
        }
      } catch (error) {
        console.error("加载消息列表失败:", error)
        
        this.$message.error("加载消息列表失败")
      } finally {
        this.loading = false
      }
    },


    async loadStats() {
      try {
        const response = await this.$http.get("/admin/messages/stats")
        if (response.data.code === 200) {
          this.stats = response.data.data || this.stats
        }
      } catch (error) {
        console.error("加载统计数据失败:", error)
        this.$message.error("加载统计数据失败")
      }
    },

    async loadSchoolOptions() {
      try {
        const response = await this.$http.get("/admin/schools/options")
        if (response.data.code === 200) {
          this.schoolOptions = response.data.data || []
        }
      } catch (error) {
        console.error("加载学校选项失败:", error)
        this.$message.error("加载学校选项失败")
      }
    },

    showBroadcastDialog() {
      this.broadcastDialogVisible = true
    },

    handleBroadcastDialogClose() {
      this.$refs.broadcastForm.resetFields()
      this.userIdInput = ''
      this.broadcastForm = {
        title: '',
        content: '',
        targetType: 'all',
        targetSchoolIds: [],
        targetUserIds: [],
        priority: 2,
        sendImmediately: true,
        scheduledTime: ''
      }
    },

    parseUserIds() {
      if (this.userIdInput.trim()) {
        const ids = this.userIdInput.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
        this.broadcastForm.targetUserIds = [...new Set(ids)]
      }
    },

    removeUserId(userId) {
      const index = this.broadcastForm.targetUserIds.indexOf(userId)
      if (index > -1) {
        this.broadcastForm.targetUserIds.splice(index, 1)
      }
    },

    useTemplate(type) {
      const templates = {
        welcome: {
          title: '欢迎使用校园帮手',
          content: '欢迎您使用校园帮手平台！在这里您可以发布和接取各种校园服务任务，包括劳务任务、跑腿服务、代课等。如有任何问题，请联系客服。'
        },
        maintenance: {
          title: '系统维护通知',
          content: '为了提供更好的服务，系统将于今晚22:00-次日6:00进行维护升级，期间可能影响部分功能使用。感谢您的理解与支持！'
        },
        activity: {
          title: '平台活动通知',
          content: '新春活动开始啦！完成指定任务即可获得丰厚奖励。活动时间有限，快来参与吧！详情请查看活动页面。'
        },
        security: {
          title: '账户安全提醒',
          content: '为了保障您的账户安全，请勿将账号密码告诉他人，定期修改密码，注意防范诈骗信息。如发现异常情况请及时联系客服。'
        }
      }
      
      if (templates[type]) {
        this.broadcastForm.title = templates[type].title
        this.broadcastForm.content = templates[type].content
      }
    },

    async handleBroadcast() {
      try {
        await this.$refs.broadcastForm.validate()
        
        // 验证发送对象
        if (this.broadcastForm.targetType === 'school' && this.broadcastForm.targetSchoolIds.length === 0) {
          this.$message.error('请选择至少一个学校')
          return
        }
        if (this.broadcastForm.targetType === 'user' && this.broadcastForm.targetUserIds.length === 0) {
          this.$message.error('请输入至少一个用户ID')
          return
        }

        this.broadcastLoading = true
        // 获取当前管理员信息
        const adminInfo = this.$store.getters.getUserInfo || { id: 1, username: '管理员' }
        
        const response = await this.$http.post("/admin/messages/broadcast", {
          ...this.broadcastForm,
          senderId: adminInfo.id,
          senderName: adminInfo.username || adminInfo.name || '管理员'
        })

        if (response.data.code === 200) {
          this.$message.success('消息发送成功')
          this.broadcastDialogVisible = false
          this.loadMessageList()
          this.loadStats()
        } else {
          this.$message.error(response.data.message || '发送失败')
        }
      } catch (error) {
        console.error('群发消息失败:', error)
        this.$message.error('发送失败')
      } finally {
        this.broadcastLoading = false
      }
    },

    handleSearch() {
      this.pagination.currentPage = 1
      this.loadMessageList()
    },

    handleView(row) {
      this.currentMessage = row
      this.detailDialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除这条消息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await this.$http.delete(`/admin/messages/${row.id}`)
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          this.loadMessageList()
          this.loadStats()
        } else {
          this.$message.error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除消息失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.loadMessageList()
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadMessageList()
    },

    getTypeColor(type) {
      const colorMap = {
        system: 'warning',
        labor: 'success',
        broadcast: 'primary',
        order: 'info'
      }
      return colorMap[type] || 'info'
    },

    getTypeName(type) {
      const nameMap = {
        system: '系统消息',
        labor: '劳务消息',
        broadcast: '群发消息',
        order: '订单消息'
      }
      return nameMap[type] || '未知'
    },

    formatDate(date) {
      if (!date) return '未知'
      return new Date(date).toLocaleString('zh-CN')
    },

    getTargetDescription() {
      switch (this.broadcastForm.targetType) {
        case 'all':
          return '所有用户'
        case 'school': {
          const schoolNames = this.schoolOptions
            .filter(school => this.broadcastForm.targetSchoolIds.includes(school.id))
            .map(school => school.name)
          return schoolNames.length > 0 ? schoolNames.join(', ') : '指定学校'
        }
        case 'user':
          return `${this.broadcastForm.targetUserIds.length} 个用户`
        default:
          return '未知'
      }
    }
  }
}
</script>

<style scoped>
.message-management {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.header-info {
  flex: 1;
}

.card-title {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-title i {
  color: #409eff;
}

.card-subtitle {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 统计卡片 */
.stats-section {
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 20px;
  color: white;
}

.total-icon {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.unread-icon {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.broadcast-icon {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.system-icon {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 消息列表 */
.message-list-section {
  margin-top: 20px;
}

.filter-bar {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

/* 对话框 */
.selected-users {
  margin-top: 10px;
}

.message-detail {
  padding: 20px 0;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-item label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
  min-width: 80px;
  flex-shrink: 0;
}

.detail-item p {
  margin: 0;
  flex: 1;
  line-height: 1.6;
}

.content-text {
  white-space: pre-wrap;
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style>
